;(function($){

    $.fn.simplemenu = function(_options) {
		if (typeof _options == 'string')
			_options = {style : _options};
        var  options = $.extend({}, $.fn.simplemenu.defaults, _options);
        return this.each(function(){
			
			var menu = $(this);
			if (options.style == 'vertical')			
				menu.addClass('vertical');
			if (options.style == 'horizontal'){
				menu.append('<li class="simple-menu-clear">#</li>');
				menu.height(menu.find('>li').height());
			}
			//level 2
			$(this).find('> li > a').hover(function(){
				var link = $(this);
				var submenu = link.next('ul');
				if (submenu.size()>0){
					if (options.style == 'vertical'){						
						submenu.css({
							left: link.parent().offset().left+link.parent().width(),
							top: link.offset().top
						}).show();
						
					} else {
						submenu.css({
							left: link.offset().left,
							top: link.parent().offset().top+link.parent().height()
						}).show();
					}
				}
			},function(e){
				var link = $(this);
				var submenu = link.next('ul');
				var related = $(e.relatedTarget);
				if (!$.fn.simplemenu.isRelated(menu,submenu,related,'ul'))
					submenu.hide();
			});
			//level 3
			$(this).find('> li > ul > li > a').hover(function(){
				var link = $(this);
				var submenu = link.next('ul');
				var parentmenu = link.parent().parent();
				if (submenu.size()>0){
					submenu.css({
						left: link.parent().offset().left - parentmenu.offset().left + link.parent().width(),
						top: link.parent().offset().top - parentmenu.offset().top
					}).show();
				}
			},function(e){
				var link = $(this);
				var submenu = link.next('ul');
				var related = $(e.relatedTarget);
				if (!$.fn.simplemenu.isRelated(menu,submenu,related,'ul'))
					submenu.hide();
			});
			// level1, level2
			$(this).find('> li > ul,> li > ul > li > ul').hover(function(){				
			},function(e){
					var submenu = $(this);
					var link = submenu.prev('a');
					var related = $(e.relatedTarget);
					if (!$.fn.simplemenu.isRelated(menu,link,related,'a'))
							submenu.hide();
			});
			
        });
    };
    $.fn.simplemenu.defaults = {
		style : 'horizontal' /* horizontal, vertical */
    };
	$.fn.simplemenu.isRelated = function(menu,target,related,tag){
		if (target.size() > 0){
			var found = related.get(0) == target.get(0);
			if (!found){
				related.parents(tag).each(function(){
					if ($(this).get(0) == target.get(0)){
						found = true;
					}
				});
			}
			return found;
		}
		return false;	
	}

})(jQuery);